package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.service.EsbProviderTreeService;
import com.sdy.dcsb.biz.service.EsbSystemService;
import com.sdy.dcsb.biz.service.UserOperationLogService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.springframework.util.StringUtils.isEmpty;

/**
 * @program: sdy-dcsb
 * @author: Lx
 * @create: 2019-09-24
 */
@Slf4j
@RestController
@RequestMapping("/esbProviderTree")
@Api(tags = "服务提供者相关接口")
public class EsbProviderTreeController extends BaseController {
    @Autowired
    private EsbProviderTreeService esbProviderTreeService;
    @Autowired
    private EsbSystemService esbSystemService;
    @Autowired
    private UserOperationLogService userOperationLogService;

    /**
     * 查询子目录
     * @param id 主键,当前节点id
     * @param haschildren ,有无子节点 1:有,0:无
     * @param unrequiredId ,不需要展示的节点id
     * @return
     */
    @GetMapping("/listMessage")
    @ApiOperation("查询子目录，最高父节点为0")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "Integer", name = "unrequiredId", value = "不需要展示的节点id"),
    })
    public Response listSubId(Integer id, Integer haschildren, Integer unrequiredId) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        QueryWrapper<EsbProviderTree> wrapper = new QueryWrapper<>();
        if (!isEmpty(haschildren)) {
            wrapper.eq("haschildren",haschildren);
        }
        if(!isEmpty(unrequiredId)) {
            wrapper.ne("id",unrequiredId);
        }
        wrapper.eq("par_id",id);
        wrapper.orderByDesc("code");
        wrapper.orderByAsc("id");
        List<EsbProviderTree> result = esbProviderTreeService.list(wrapper);
        List<EsbProviderTreeCount> resultCount = new ArrayList();
        for(int i=0; i< result.size(); i++) {
            EsbProviderTreeCount esbProviderTreeCount = new EsbProviderTreeCount();
            esbProviderTreeCount.setId(result.get(i).getId());
            esbProviderTreeCount.setCode(result.get(i).getCode());
            esbProviderTreeCount.setHaschildren(result.get(i).getHaschildren());
            esbProviderTreeCount.setLvl(result.get(i).getLvl());
            esbProviderTreeCount.setName(result.get(i).getName());
            esbProviderTreeCount.setStatus(result.get(i).getStatus());
            esbProviderTreeCount.setParId(result.get(i).getParId());
            esbProviderTreeCount.setCount(systemCount(result.get(i).getId(), 0));
            resultCount.add(i, esbProviderTreeCount);
        }
        return Response.success(resultCount);
    }

    @GetMapping("/insert")
    @ApiOperation("新增当前目录的子目录")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "lvl", value = "当前节点层级"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "目录名称"),
    })
    public Response insert(HttpServletRequest request, Integer id, Integer lvl, Integer haschildren, String name) {
        if(isEmpty(id) || isEmpty(lvl)) {
            return Response.error("当前节点id或层级不能为空");
        }
        if (haschildren == 1) {
            EsbProviderTree esbProviderTree = new EsbProviderTree();
            if (!isEmpty(name)) {
                try {
                    name = URLDecoder.decode(name,"UTF-8");
                } catch (UnsupportedEncodingException e) {

                }
                esbProviderTree.setCode(0);
                esbProviderTree.setLvl(lvl + 1);
                esbProviderTree.setHaschildren(1);
                esbProviderTree.setName(name);
                esbProviderTree.setStatus("1");
                esbProviderTree.setParId(id);
                userOperationLogService.savaUserLog(request, "新增提供者树目录：" + name);
                return Response.success(esbProviderTreeService.save(esbProviderTree));
            }else {
                return Response.error("目录名不能为空");
            }
        }else {
            return Response.error("当前目录无法新增");
        }
    }

    @GetMapping("/updateDirName")
    @ApiOperation("修改目录名称")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "目录名称"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
    })
    public Response updateName(HttpServletRequest request, Integer id, String name, Integer haschildren) {
        if(!isEmpty(id)) {
            EsbProviderTree esbProviderTree = new EsbProviderTree();
            if (haschildren == 1) {
                if(!isEmpty(name)) {
                    try {
                        name = URLDecoder.decode(name,"utf-8");
                    }catch(IOException e) {

                    }
                    esbProviderTree.setName(name);
                    userOperationLogService.savaUserLog(request, "修改提供者树目录："+ esbProviderTreeService.getById(id).getName() +
                            "--->" + name);
                    return Response.success(esbProviderTreeService.update(esbProviderTree, new UpdateWrapper<EsbProviderTree>().eq("id", id)));
                }else {
                    return Response.error("目录名称不能为空");
                }

            }else {
                return Response.error("当前目录名称不能被修改");
            }
        }else {
            return Response.error("请求节点id不能为空");
        }
    }

    /**
     * 目录迁移
     */
    @ApiOperation("目录迁移")
    @GetMapping("/dirMigration")
    public Response dirMigration(HttpServletRequest request, Integer id, Integer targetId, Integer targetLvl) {
        if(isEmpty(id) || isEmpty(targetId) || isEmpty(targetLvl)) {
            return Response.error("当前节点id或目标节点id或层级不能为空");
        }
        if(id.equals(targetId)) {
            return Response.error("不能迁移到自己目录下，请重新选择!");
        }
        EsbProviderTree esbProviderTre = new EsbProviderTree();
        esbProviderTre.setLvl(targetLvl + 1);
        esbProviderTre.setParId(targetId);
        userOperationLogService.savaUserLog(request, "迁移提供者树目录：" + esbProviderTreeService.getById(id).getName() +
                "--->" + esbProviderTreeService.getById(targetId).getName());
        esbProviderTreeService.update(esbProviderTre,new UpdateWrapper<EsbProviderTree>().eq("id",id));
        return Response.success("迁移成功");
    }

    /**
     * 删除目录
     */
    @ApiOperation("删除目录")
    @GetMapping("/deleteById")
    public Response deleteById(HttpServletRequest request, Integer id,Integer hasChildren) {
        if(isEmpty(id)) {
            return Response.error("当前节点id不能为空");
        }
        if (hasChildren == 1) {
            QueryWrapper<EsbProviderTree> wrapper = new QueryWrapper<>();
            wrapper.eq("par_id",id);
            List<EsbProviderTree> result = esbProviderTreeService.list(wrapper);
            if(result.size() >= 1 || id == 1) {
                return Response.error("当前目录下有数据不能被删除！");
            }else {
                userOperationLogService.savaUserLog(request, "删除提供者树目录：" + esbProviderTreeService.getById(id).getName());
                if(esbProviderTreeService.removeById(id)) {
                    return Response.success("删除目录成功");
                }else {
                    return Response.error("删除目录失败！");
                }
            }
        }else {
            return Response.error("当前目录不能被删除");
        }
    }

    @GetMapping("/selectTargetDirMess")
    @ApiOperation("查询当前目录下的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
    })
    public Response selectTargetDirMess(Integer id) {
        if(isEmpty(id)) {
            return Response.error("当前节点id不能为空");
        }
        QueryWrapper<EsbProviderTree> wrapper = new QueryWrapper<>();
        wrapper.eq("par_id",id);
        wrapper.eq("hasChildren",0);
        List<EsbProviderTree> list = esbProviderTreeService.list(wrapper);
        return Response.success(list);
    }

    /**
     * 查询数据
     * @param id ,当前节点id
     * @return
     */
    @GetMapping("/selectTargetMess")
    @ApiOperation("查询当前节点目录数据,haschildren=1时调用此接口")
    public Response selectTargetMess(Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }else {
            return Response.success(esbSystemService.getById(id));
        }
    }

    @GetMapping("/selectByName")
    @ApiOperation("提供者信息查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "String", name = "systemName", value = "查询值"),
            @ApiImplicitParam(dataType = "String", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "String", name = "size", value = "每页数量"),
    })
    public Response selectByName(Integer id, String systemName, Integer current, Integer size) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        JSONObject object = new JSONObject();
        if(isEmpty(current)) {
            current = 1;
        }
        if(isEmpty(size)) {
            size = 10;
        }
        object.put("size",size);
        object.put("current",current);
        object.put("searchCount",true);

        Integer total = 0;
        Integer page = 0;

        if(!isEmpty(systemName)) {
            try {
                systemName = URLDecoder.decode(systemName,"utf-8");
            } catch (UnsupportedEncodingException e) {

            }
            List<EsbSystemVo> resultCount = esbSystemService.queryCountSystemByIdMess(id, systemName);
            total = resultCount.size();
            if(total%size==0){
                page = total/size;
            }else {
                page = total/size+1;
            }
            List<EsbSystemVo> result = esbSystemService.queryAllSystemByIdMess(id, current, size, systemName);
            object.put("records",result);
            object.put("total",total);
            object.put("pages",page);

        }else {
            List<EsbSystemVo> resultCount = esbSystemService.queryCountSystemById(id);
            total = resultCount.size();
            if(total%size==0){
                page = total/size;
            }else {
                page = total/size+1;
            }
            List<EsbSystemVo> result = esbSystemService.queryAllSystemById(id, current, size);
            object.put("records",result);
            object.put("total",total);
            object.put("pages",page);
        }
        return Response.success(object);

    }

    /**
     * 新建系统
     */
    @ApiOperation("新建系统")
    @GetMapping("/insertSystem")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "lvl", value = "节点层级"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "String", name = "systemName", value = "系统名称"),
            @ApiImplicitParam(dataType = "String", name = "systemCode", value = "系统编码"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "系统联系人"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "手机/电话/qq"),
            @ApiImplicitParam(dataType = "String", name = "manageName", value = "管理部门"),
    })
    public Response insertSystem(HttpServletRequest request, Integer id, Integer lvl, Integer haschildren, String systemName, String systemCode,
                                 String pName, String pPhone, String manageName) {
        if(isEmpty(id) || isEmpty(lvl)) {
            return Response.error("当前节点id或层级不能为空");
        }
        try {
            systemName = URLDecoder.decode(systemName,"utf-8");
            if(!isEmpty(systemCode)){
                systemCode = URLDecoder.decode(systemCode,"utf-8");
            }
            if(!isEmpty(pName)){
                pName = URLDecoder.decode(pName,"utf-8");
            }
            if(!isEmpty(pPhone)) {
                pPhone = URLDecoder.decode(pPhone,"utf-8");
            }
            if(!isEmpty(manageName)) {
                manageName = URLDecoder.decode(manageName,"utf-8");
            }
        } catch (UnsupportedEncodingException e) {

        }
        if (1 == haschildren) {
            EsbSystem esbSystem = new EsbSystem();
            esbSystem.setSystemName(systemName);
            esbSystem.setManageName(manageName);
            esbSystem.setPName(pName);
            esbSystem.setPPhone(pPhone);
            esbSystem.setSystemCode(systemCode);
            esbSystem.setStatus("1");
            if (esbSystemService.save(esbSystem)) {
                userOperationLogService.savaUserLog(request, "新增提供者系统：" + systemName);
                EsbProviderTree esbProviderTree = new EsbProviderTree();
                esbProviderTree.setCode(esbSystem.getId());
                esbProviderTree.setLvl(lvl + 1);
                esbProviderTree.setParId(id);
                esbProviderTree.setName(systemName);
                esbProviderTree.setHaschildren(0);
                esbProviderTree.setStatus("1");
                if (esbProviderTreeService.save(esbProviderTree)) {
                    userOperationLogService.savaUserLog(request, "新增提供者树目录：" + systemName);
                    return Response.success("新增提供者系统成功");
                }else {
                    return Response.error("新增提供者树目录失败");
                }
            }else {
                return Response.error("新增提供者系统失败");
            }
        }else {
            return Response.error("此目录下不能新建系统");
        }
    }

    /**
     * 修改系统信息
     */
    @GetMapping("/update")
    @ApiOperation("修改单条系统信息，系统编码不可修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前系统id"),
            @ApiImplicitParam(dataType = "String", name = "systemName", value = "系统名称"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "系统联系人"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "手机/电话号码/QQ"),
            @ApiImplicitParam(dataType = "String", name = "manageName", value = "管理部门"),
    })
    public Response update(HttpServletRequest request, Integer id, String systemName, String pName, String pPhone, String manageName) {
        try {
            if(!isEmpty(systemName)) {
                systemName = URLDecoder.decode(systemName,"utf-8");
            }
            if(!isEmpty(pName)) {
                pName = URLDecoder.decode(pName,"utf-8");
            }
            if(!isEmpty(pPhone)) {
                pPhone = URLDecoder.decode(pPhone,"utf-8");
            }
            if(!isEmpty(manageName)) {
                manageName = URLDecoder.decode(manageName,"utf-8");
            }

        }catch(IOException e) {

        }

        if(!isEmpty(systemName)) {
            QueryWrapper<EsbSystem> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            List<EsbSystem> result = esbSystemService.list(wrapper);
            if (result.size() == 0){
                return Response.error("此id没有与之对应的系统信息");
            }

            EsbSystem esbSystem = new EsbSystem();
            EsbProviderTree esbProviderTree = new EsbProviderTree();

            Integer i = 0;
            Integer j = 0;

            if(!Objects.equals(result.get(0).getSystemName(), systemName)) {
                esbSystem.setSystemName(systemName);
                i++;
                esbProviderTree.setName(systemName);
                j++;
            }
            if(!Objects.equals(result.get(0).getPName(), pName)) {
                if(!isEmpty(pName)){
                    esbSystem.setPName(pName);
                }else {
                    esbSystem.setPName("");
                }
                i++;
            }
            if(!Objects.equals(result.get(0).getPPhone(), pPhone)) {
                if(!isEmpty(pPhone)){
                    esbSystem.setPPhone(pPhone);
                }else {
                    esbSystem.setPPhone("");
                }
                i++;
            }
            if(!Objects.equals(result.get(0).getManageName(), manageName)) {
                if(!isEmpty(manageName)){
                    esbSystem.setManageName(manageName);
                }else {
                    esbSystem.setManageName("");
                }
                i++;
            }
            if(i >= 1) {
                userOperationLogService.savaUserLog(request, "修改提供者系统：" + esbSystemService.getById(id).getSystemName());
                boolean type = esbSystemService.update(esbSystem, new UpdateWrapper<EsbSystem>().eq("id", id));
                if(type) {
                    if(j >= 1){
                        userOperationLogService.savaUserLog(request, "修改提供者树目录："+
                                esbSystemService.getById(id).getSystemName() + "--->" + systemName);
                        boolean treeType = esbProviderTreeService.update(esbProviderTree, new UpdateWrapper<EsbProviderTree>().eq("code",id));
                        if(treeType){

                        }else {
                            return Response.error("树信息修改失败");
                        }
                    }
                    return Response.success("信息修改成功");
                }else {
                    return Response.error("信息修改失败");
                }
            }else {
                return Response.error("信息无变化");
            }
        }else {
            return Response.error("系统名称不能为空");
        }
    }

    /**
     *删除系统
     */
    @ApiOperation("删除系统")
    @GetMapping("/removeById")
    public Response removeById(HttpServletRequest request, Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        String name = esbSystemService.getById(id).getSystemName();
        userOperationLogService.savaUserLog(request, "删除提供者系统：" + name);
        if (esbSystemService.removeById(id)) {
            QueryWrapper<EsbProviderTree> wrapper = new QueryWrapper<>();
            wrapper.eq("code",id);
            userOperationLogService.savaUserLog(request, "删除提供者树目录：" + name);
            esbProviderTreeService.remove(wrapper);
            return Response.success("提供者系统信息删除成功");
        }else {
            return Response.error("网络故障，删除系统信息失败");
        }
    }

    /**
     * 详情
     */
    @ApiOperation("详情接口")
    @GetMapping("/selectById")
    public Response select(Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }else {
            return Response.success(esbSystemService.getById(id));
        }
    }

    /**
     * 查询当前目录下消费者系统数量
     * @param id 当前节点id
     * @param count 初始值0
     * @return
     */
    private Integer systemCount(Integer id, Integer count) {
        QueryWrapper<EsbProviderTree> wrapperSystem = new QueryWrapper<>();
        wrapperSystem.eq("par_id",id);
        wrapperSystem.ne("code",0);
        List<EsbProviderTree> resultSystem = esbProviderTreeService.list(wrapperSystem);
        count = count + resultSystem.size();
        QueryWrapper<EsbProviderTree> wrapper = new QueryWrapper<>();
        wrapper.eq("par_id",id);
        wrapper.eq("code",0);
        List<EsbProviderTree> result = esbProviderTreeService.list(wrapper);
        for(int i=0; i<result.size(); i++) {
            count = systemCount(result.get(i).getId(), count);
        }
        return count;
    }

}